var generatorDataSource =
  window.localStorage.getItem('generatorDataSource') || '',
  generatorTableSchema =
    window.localStorage.getItem('generatorTableSchema') || '',
  generatorTableName = window.localStorage.getItem('generatorTableName') || ''

function refreshDataSource() {
  layui.use(['form'], function () {
    var $ = layui.$,
      form = layui.form

    $.get('/generator/dataSource/list', function (response) {
      $('.searchForm #dataSource').html('')
      $('.searchForm #dataSource').append(
        '<option value = "">请选择数据源</option>'
      )
      response.data.forEach(item => {
        var selected = generatorDataSource == item.id ? 'selected' : ''
        $('.searchForm #dataSource').append(
          '<option value=' +
          item.id +
          ' ' +
          selected +
          '>' +
          item.alias +
          '</option>'
        )
      })
      if (generatorDataSource) {
        $.get(
          '/generator/schema/list', {
            id: generatorDataSource
          },
          function (response) {
            $('.searchForm #tableSchema').html('')
            response.data.forEach(item => {
              var selected = generatorTableSchema == item ? 'selected' : ''
              $('.searchForm #tableSchema').append(
                '<option value=' +
                item +
                ' ' +
                selected +
                '>' +
                item +
                '</option>'
              )
            })
            $.get(
              '/generator/table/list', {
                id: generatorDataSource,
                tableSchema: generatorTableSchema
              },
              function (response) {
                $('.searchForm #tableName').html('')
                response.data.forEach(item => {
                  var selected =
                      generatorTableName == item.tableName ? 'selected' : ''
                  $('.searchForm #tableName').append(
                      '<option data-tableComment="' + item.tableComment + '" value=' +
                      item.tableName +
                      ' ' +
                      selected +
                      '>' +
                      item.tableName +
                      ' ' +
                      item.tableComment +
                      '</option>'
                  )
                })
              }
            )
          }
        )
      }
      //表单重新渲染，要不然添加完显示不出来新的option
      form.render()
    })
  })
}

layui.use(['form', 'layer', 'table'], function () {
  var form = layui.form,
    layer = layui.layer, //弹层
    table = layui.table //表格

  form.render()

  var $ = layui.$,
    dataSource = $('.searchForm #dataSource'),
    tableName = $('.searchForm #tableName'),
    tableSchema = $('.searchForm #tableSchema')

  //执行一个 table 实例
  var tableInit = table.render({
    id: 'generator',
    elem: '#generatorTable',
    // height: 'full-250',
    url: '/generator/column/list', //数据接口,
    title: '数据库表',
    page: false, //开启分页,
    parseData: function (res) {
      //res 即为原始返回的数据
      return {
        code: res.code, //解析接口状态
        msg: res.msg, //解析提示文本
        count: res.data.length, //解析数据长度
        data: res.data //解析数据列表
      }
    },
    where: {
      id: generatorDataSource,
      tableName: generatorTableName,
      tableSchema: generatorTableSchema
    },
    even: false, //开启隔行背景
    toolbar: '#backendToolbar',
    defaultToolbar: ['filter', 'exports', 'print'],
    totalRow: false, //开启合计行,
    cols: [
      [
        //表头

        {
          field: 'columnName',
          title: '列名',
          fixed: 'left'
        },
        {
          field: 'columnComment',
          title: '列注释'
        },
        {
          field: 'columnKey',
          title: '是否主键',
          align: 'center',
          templet: function (d) {
            if (d.columnKey === 'PRI') {
              return '<span class="layui-badge layui-bg-orange">主键</span>'
            } else {
              return ''
            }
          }
        },
        {
          field: 'isNullable',
          title: '可为空'
        },
        {
          field: 'dataType',
          title: '数据类型',
          hide: true
        },
        {
          field: 'columnType',
          title: '列值属性'
        },
        {
          field: 'characterMaximumLength',
          title: '字符串最大长度',
          hide: true
        },
        {
          field: 'numericPrecision',
          title: '数字类型长度',
          hide: true
        },
        {
          field: 'numericScale',
          title: '精度',
          hide: true
        },
        {
          field: 'extra',
          title: '其他',
          align: 'center',
          templet: function (d) {
            if (d.extra === 'auto_increment') {
              return '<span class="layui-badge layui-bg-blue">自增</span>'
            } else {
              return ''
            }
          }
        },
        {
          fixed: 'right',
          width: 165,
          title: '操作',
          align: 'center',
          toolbar: '#backendBar'
        }
      ]
    ]
  })

  var active = {
    reload: function () {
      // 执行重载
      table.reload('generator', {
        where: {
          id: dataSource.val(),
          tableName: tableName.val(),
          tableSchema: tableSchema.val()
        }
      })
      return false
    }
  }

  //监听头工具栏事件
  table.on('toolbar(generatorFilter)', function (obj) {
    var checkStatus = table.checkStatus(obj.config.id),
      data = checkStatus.data //获取选中的数据
    switch (obj.event) {
      case 'config':
        $.get(
          '/generator/config', {},
          function (str) {
            layer.open({
              type: 1,
              shadeClose: true,
              title: '生成配置',
              area: ['100%', '100%'],
              content: str //注意，如果str是object，那么需要字符拼接。
            })
          }
        )
        break
      case 'delete':
        if (data.length === 0) {
          layer.msg('请选择一行')
        } else {
          data.forEach(row => {
            //向服务端发送删除指令
            $.post('/code/db/delete/' + row.id, function (response) {
              layer.msg(response.data, {
                time: 1000,
                icon: 1
              })
              tableInit.reload()
            })
          })
        }
        break
    }
  })

  $(function () {
    refreshDataSource()
  })

  form.on('select(dataSource)', function (data) {
    window.localStorage.setItem('generatorDataSource', data.value)
    $('.searchForm #tableSchema').html('')
    $.get(
      '/generator/schema/list', {
        id: data.value
      },
      function (response) {
        response.data.forEach((item, index) => {
          var selected = index === 0 ? 'selected' : ''
          $('.searchForm #tableSchema').append(
            '<option value=' + item + ' ' + selected + '>' + item + '</option>'
          )
        })
        form.render() //表单重新渲染，要不然添加完显示不出来新的option
      }
    )
  })

  form.on('select(tableSchema)', function (data) {
    window.localStorage.setItem('generatorTableSchema', data.value)
    $('.searchForm #tableName').html('')
    $.get(
      '/generator/table/list', {
        id: $('.searchForm #dataSource').val(),
        tableSchema: data.value
      },
      function (response) {
        response.data.forEach((item, index) => {
          var selected = index === 0 ? 'selected' : ''
          $('.searchForm #tableName').append(
            '<option value=' +
            item.tableName +
            ' ' +
            selected +
            '>' +
            item.tableName +
            ' ' +
            item.tableComment +
            '</option>'
          )
        })
        form.render() //表单重新渲染，要不然添加完显示不出来新的option
      }
    )
  })

  form.on('select(tableName)', function (data) {
    window.localStorage.setItem('generatorTableName', data.value)
  })

  $('.searchForm .layui-btn').on('click', function () {
    var type = $(this).data('type')
    active[type] ? active[type].call(this) : ''
  })
})
